package com.cn.wanxi.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

public class FileUpload {
    private static String filename = null;
    private static String imgHref = "";

    public static String upload(HttpServletRequest req, String direcoty) throws IOException {

//        创建一个工厂--用来装前端传递过来的文件
        DiskFileItemFactory factory = new DiskFileItemFactory();
//        用servlet来解析加载的文件
        ServletFileUpload upload = new ServletFileUpload(factory);
//        设置工厂的最大值（规定传递过来的文件最大值）
        factory.setSizeThreshold(1024 * 1024);
        List items = null;
        try {
//            Integer.parseInt("aaa");
//            将前程传递过来的数据强制转换为文件
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
//        Iterator迭代器：list和Iterator的区别？多线程
//        Iterator单线程安全
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
//            将当前的数据强制转换为文件类型
            FileItem item = (FileItem) iter.next();
//            isFormField判断是否为文件
            if (!item.isFormField()) {
                // 根据时间戳创建头像文件
//                filename = System.currentTimeMillis() + ".jpg";
//                怎么拿到页面传递过来的文件名？
//                4312432341234---a.jpg
                filename = System.currentTimeMillis() + "---" + item.getName();
                System.out.println(req.getContextPath());
                /*File f = new File(getServletContext().getRealPath("upload"));*/
                String path = req.getServletContext().getRealPath("/");
                String outPath = path;
                String[] outs = path.split("out");
                path = outs[0] + "/web/" + direcoty;
                System.out.println(path);
                File f = new File(path);
                if (!f.exists()) {
                    f.mkdir();
                }
                String imgsrc = f + "/" + filename;
                imgHref = direcoty + filename;//将web下面的保存路径返回给前端
                // 复制文件
//                item.getInputStream()将文件放入输入流里面准备读取
                InputStream is = item.getInputStream();
//                将读取的数据写入到指定的路径里面
                FileOutputStream fos = new FileOutputStream(imgsrc);
//                byte b[] = new byte[1024 * 1024];
                File outFile = new File(outPath + direcoty + filename);
                FileOutputStream outFos = new FileOutputStream(outFile);
                int length = 0;
                while (-1 != (length = is.read())) {
                    fos.write(length);
                    outFos.write(length);//将文件复制到编译后的out文件里面取
//                    fos.write(b, 0, length);
                }
                fos.flush();
                fos.close();
            } else {
//                普通数据
                System.out.println(item.getFieldName());
                String value = item.getString();
                value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
                System.out.println(value);
            }
        }
        return imgHref;
    }
}
